package hu.bme.aut.consulttime.server.file;

import hu.bme.aut.consulttime.server.entities.Log;
import hu.bme.aut.consulttime.server.entityservices.EntityManagerFactoryWrapper;

import java.io.IOException;
import java.io.OutputStream;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LogFileDownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 667L;
	
	public static final EntityManager entityManager() {
		return EntityManagerFactoryWrapper.get().createEntityManager();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String logIdString = req.getParameter("logid");
		long logId = Long.valueOf(logIdString);
		Log log = null;
		
		EntityManager em = entityManager();
		
		try {
			log = em.find(Log.class, logId);
		} 
		catch (Throwable t) {
			t.printStackTrace();
		} 
		finally {
			em.close();
		} 
		
		resp.setContentType("application/octet-stream");  
		resp.setHeader("Content-disposition", "attachment; filename=\"" + log.getAttachedFileName()+ "\"");
		
		
		byte[] logFileBytes = log.getAttachedFile();
		
		 OutputStream os = resp.getOutputStream();  
		 os.write(logFileBytes);
		 os.flush();  
		 os.close();   
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
